package com.mapbar.pay.dao.impl;

import com.mapbar.pay.dao.UserDao;
import com.mapbar.pay.entity.Device;
import com.mapbar.pay.entity.User;
import com.mapbar.pay.util.ProjectUtil;
import com.mapbar.pay.util.Util;
import com.mapbar.util.IDCodec;
import com.mapbar.util.TextCodec;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 *@Date 创建时间 2010-03-04 09:14:54
 *@author fengbj
 * 
 */
public class UserDaoImpl implements UserDao {

    public Logger logger = Logger.getLogger(this.getClass());//日志对象

    /**
     * 用户登录
     * @param userName
     * @param pwd
     * @return 返回User对象，如果为空表示登录失败
     */
    public User logon(String userName, String pwd) {

        if (userName == null || pwd == null) {
            return null;
        } else {
            //初始化参数
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", userName);
            map.put("pass", pwd);

            //获取接口返回值
            String src = Util.getSrc(Util.getUrl(ProjectUtil.LOGON_URL), map);
            if (src == null) {
                logger.error("接口 " + Util.getUrl(ProjectUtil.LOGON_URL) + "请求异常，userName = [" + userName + "] , pwd = [" + pwd + "]");
            } else {
                logger.info("接口 " + Util.getUrl(ProjectUtil.LOGON_URL) + "，请求参数userName = [" + userName + "] , pwd = [" + pwd + "] ， 返回值 ：" + src);

                //解析json
                JSONObject json = null;
                try {
                    json = Util.initJSONObject(src);
                    if (json.getString("userId") != null && !"".equals(json.getString("userId"))) {

                        User user = new User();

                        if (json.getString("serial") != null) {
                            user.setSerial(json.getString("serial").trim());
                        }
                        user.setUserId(Integer.parseInt(json.getString("userId").trim()));
                        user.setUserIdc(IDCodec.encode(TextCodec.encode(user.getUserId() + "")));
                        user.setUserName(userName);

                        logger.info("登录成功，user[" + user.toString() + "]");

                        return user;
                    } else {
                        logger.info("登录失败，[userName=" + userName + ",pwd=" + pwd + "]");
                        return null;
                    }

                } catch (Exception e) {

                    logger.error("解析json异常 json =[" + src + "], userName=[" + userName + "],pwd=[" + pwd + "]" + e.toString());
                } finally {
                    json = null;
                    src = null;
                    map = null;
                }

            }
            return null;
        }

    }

    /**
     * 当用户信息过期时刷新用户信息
     * @param user
     * @return 更新后用户信息
     */
    @Override
    public void refreshUserInfo(User user) {

        if (user == null || user.getUserName() == null || user.getUserIdc() == null) {
            return;
        } else {
            //初始化参数
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", user.getUserName());
            map.put("idc", user.getUserIdc().replaceAll("%", "{_}"));

            //获取接口返回值
            String src = Util.getSrc(Util.getUrl(ProjectUtil.REFRESH_USER_INFO), map);
            if (src == null) {
                logger.error("接口 " + Util.getUrl(ProjectUtil.REFRESH_USER_INFO) + "请求异常，userName = [" + user.toString() + "]");
            } else {
                logger.info("接口 " + Util.getUrl(ProjectUtil.REFRESH_USER_INFO) + "，userName = [" + user.toString() + "]， 返回值 ：" + src);

                //解析json
                JSONObject json = null;
                try {
                    json = Util.initJSONObject(src);

                    if (json.getString("serial") != null) {
                        user.setSerial(json.getString("serial").trim());
                    }

                    logger.info("请求登录接口成功，" + Util.getUrl(ProjectUtil.REFRESH_USER_INFO) + "user[" + user.toString() + "]");

                    //return user;
                } catch (Exception e) {

                    logger.error("解析json异常，json=[" + src + "], userName=[" + user.toString() + "]" + e.toString());
                } finally {
                    json = null;
                    src = null;
                    map = null;
                }

            }
            //return null;
        }
        //return null;
    }

    @Override
    public User reg(String userName, String userPwd, String userEmail, String userPhone, String userSeria, String type) {
        if (userName == null || "".equals(userName.trim())
                || userPwd == null || "".equals(userPwd.trim())
                || userEmail == null || "".equals(userEmail.trim())) {
            return null;
        }
        if(userPhone == null){
            userPhone = "";
        }
        if(userSeria == null){
            userSeria = "";
        }

        String postData = "<data><userInfo><userName>" + userName
                + "</userName><password>" + userPwd
                + "</password><confirmPassword>" + userPwd
                + "</confirmPassword><nickName>" + ""
                + "</nickName><email>" + userEmail + "</email><mobile>" + userPhone
                + "</mobile></userInfo><mobileinfo><equipment>1</equipment><deviceid>"
                + userSeria + "</deviceid><mobileorpnd>" + type + "</mobileorpnd></mobileinfo></data>";
        //System.out.println(postData);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("postData", postData);

        String src = Util.getSrc(Util.getUrl(ProjectUtil.REG), params);
        if (src == null) {
            return null;
        }
        SAXReader saxReader = new SAXReader();
        Document document;
        String result = null;
        User user = new User();
        user.setUserName(userName);
        user.setSerial(userSeria);
        try {
            document = saxReader.read(new ByteArrayInputStream(src.getBytes("utf-8")));

            Node auth = document.selectSingleNode("//result/rs/auth/text()");

            if (auth != null) {
                if (auth.getText().equalsIgnoreCase("true")) {
                    //注册成功
                    //flag = true;
                    user = this.logon(userName, userPwd);
                    //if(!"".equals(userSeria)){
                     //   user.setSerial(userSeria);
                    //}
                    return user;
                    
                } else {
                    //flag = false;
                    Node msg = document.selectSingleNode("//result/rs/message/text()");
                    if (msg != null) {
                        result = msg.getText();
                        msg  = null;
                    } else {
                        result = "用户已存在！";
                    }
                }
            }

            user.setNote(result);
            logger.info("注册成功："+user);
            return user;
        } catch (Exception e) {
            //flag = false;
            logger.error("注册异常["+user+"]"+e.toString());
            return null;
        }finally{
            saxReader = null;
            document = null;

        }
    }


}
